#!/usr/bin/env python
# -*- coding: utf-8 -*-
from typing import TypeVar

from sqlalchemy import and_
from sqlalchemy.orm import Session

from app.common.page import PageParam
from app.models import User
from pydantic import BaseModel

from app.dao.base_dao import BaseDao
from app.db.base_class import Base
from app.models.bar import Bar
from app.models.constant import Constant
from app.models.favorite import Favorite
from app.models.instrument import Instrument
from app.models.position import Position
from app.models.user_setting import UserSetting
from app.schemas.bar import CandlestickQuery


class PositionDao(BaseDao[Position]):
    def __init__(self):
        super(PositionDao, self).__init__()
        self.modelClass = Position
        self.id = Position.id

    def selectUserPositions(self, db: Session, queryWrapper: CandlestickQuery):
        result = db.query(Instrument.id, Position.id.label('positionId'), Instrument.name, Instrument.symbol, Bar.close, Bar.open, Bar.low, Bar.high,
                          Bar.volume, Bar.amount, Bar.barDate, Bar.preClose,
                          Position.cost, Position.num, Position.state, Position.startDate, Position.endDate) \
            .select_from(Position) \
            .outerjoin(Instrument, Position.instrumentId == Instrument.id) \
            .outerjoin(Bar, and_(Position.instrumentId == Bar.instrumentId,
                       Bar.barDate == queryWrapper.barDate,
                       Bar.frequency == queryWrapper.frequency,
                       Bar.adjustFlag == queryWrapper.adjust)) \
            .filter(
            Position.userId == queryWrapper.userId,
            Position.state == queryWrapper.state,
            Instrument.marketType == queryWrapper.marketType) \
            .order_by(Instrument.symbol.asc()) \
            .all()
        return result

positionDao = PositionDao()
